<template>
    <span v-show="isShow">
        <van-uploader ref="uploader" class="btn" :before-read="beforeRead" :after-read="afterRead" >
            <span></span>
        </van-uploader>
    </span>
</template>

<script>
import Vue from 'vue'
import { Uploader, Icon } from 'vant'

// 自定义方法
import { ImageCompress } from '_commonFn/image'
import { failTextVantToa, loadingVantToa, clearVantToa } from "_projectFn/prompt"
import { upLoadImg } from '_network/request'

Vue.use(Uploader).use(Icon)

export default {
    name: 'ImgUpLoad',
    props: {
        // 1MB等于1024KB；1024KB等于1048576byte，1MB等于1048576byte。
        maxSize: {
            type: Number,
            default: 10485760, // 10M，单位byte
        },
        isShow: {
            type: Boolean,
            default: false,
        }
    },
    data() {
        return {
            imageCompress: new ImageCompress(),
            uploadType: '',
        }
    },
    methods: {
        choose(type = '') {
            this.uploadType = type
            this.$refs.uploader.chooseFile()
        },
        // 上传前
        beforeRead(file) {
            loadingVantToa({})
            return true
        },
        // 上传后
        async afterRead(file) {
            const compressFile = await this.imageCompress.compress(file.file)
            const res = await upLoadImg({
                file: compressFile,
                fileName: file.file.name,
            })
            // console.log('res', res)
            if (res.errcode == 1000 && Array.isArray(res.data) && res.data[0] && res.data[0].FileUrl) {
                this.$emit('imgUpLoadSuccess', res.data[0].FileUrl, this.uploadType)
            }
            clearVantToa()
        },
    },
}
</script>

<style lang="scss" scoped>
.btn {
    cursor: pointer;
    
    .img-icon {
        font-size: 22px;
        color: #bec2c1;
    }
}
</style>